import { useRef, useState } from 'react';
import { FooterToolbar, ProForm, ProFormText, ProFormSelect } from '@ant-design/pro-components';
import { Button, message, Space } from 'antd';
import { history } from 'umi';
import { PageContainer } from '@ant-design/pro-components';
import { redispoolDetail, redispoolEdit } from '@/services/server';
import useDetailType from '@/hooks/useDetailType';
import StorageManager from '@/utils/StorageManager';

import type { ProFormInstance } from '@ant-design/pro-components';

interface IParams {
  type?: string;
  id?: string;
}

import styles from './style.less';

const regexNum = /^[0-9.]*$/;
const regexIP =
  /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;

const defaultValues = {
  siteTag: 'KS',
  redisIp: '',
  redisDesc: '',
  redisPort: '',
  redisType: '',
  maxTotal: '',
  maxIdle: '',
  maxWait: '',
  testOnBorrow: false,
  testOnReturn: false,
  otherRedisIp: '',
  redis1Cluster: '',
  redis2Ip: '',
  redis3Cluster: '',
  redis4Cluster: '',
};

const SensitizeManageDetail: React.FC = () => {
  const { isAdd, isModify, params } = useDetailType<IParams>();
  const formRef = useRef<ProFormInstance>();
  const [activityDisabeld, setActivityDisabeld] = useState(false);

  const eunmList: any = StorageManager.getLocalStorageSync('eunmList');
  const OptionsSiteTagList = eunmList?.OptionsSiteTagList || [];

  // 新增或者编辑  表单内容-初始化
  const getDetail = async () => {
    // 编辑
    if (params.id && isModify) {
      setActivityDisabeld(true);
      const { code, data } = await redispoolDetail({
        id: params.id,
      });
      if (code === 200 && data) {
        return {
          ...data,
        };
      }
    }
    // 新增直接过来的
    if (params.id && isAdd) {
      setActivityDisabeld(true);
      return { ...defaultValues, activityId: params.id };
    }
    return { ...defaultValues };
  };

  const goToList = () => {
    history.push('/server/redisConfig/List');
  };

  const restProForm = () => {
    formRef.current?.setFieldsValue({
      ...defaultValues,
      activityId: activityDisabeld ? params.id : '',
    });
  };

  const onValueChange = (value: any) => {
    console.log(value, 'onValueChange');
  };

  const onFinish = async (value: Partial<API.CodegroupEditInfo>) => {
    console.log('onFinish---value', isAdd, isModify, value);
    const param: API.CodegroupEditInfo = {
      ...value,
    };
    // 编辑
    if (isModify && params.id) {
      param.id = params.id;
    }
    const { data, code } = await redispoolEdit(param);
    if (code === 200) {
      message.success('保存成功');
      goToList();
    }
  };

  return (
    <PageContainer>
      <div className={styles['detail-body']}>
        <>
          <ProForm<Partial<API.CodegroupListItem>>
            formRef={formRef}
            layout="horizontal"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
            scrollToFirstError
            onValuesChange={onValueChange}
            onFinish={onFinish}
            //@ts-ignore
            request={getDetail}
            submitter={{
              searchConfig: {
                resetText: '返回',
              },
              render: (_, dom) => (
                <FooterToolbar
                  extra={
                    <div style={{ textAlign: 'center', padding: '5px 0' }}>
                      <Space>
                        <Button type="primary" onClick={restProForm}>
                          重置
                        </Button>
                        <Button onClick={goToList}>返回</Button>
                        {dom[1]}
                      </Space>
                    </div>
                  }
                />
              ),
            }}
          >
            <>
              <ProForm.Group>
                <ProFormSelect labelCol={{ span: 8 }} width="lg" name="id" label="id" hidden />
                <ProFormSelect
                  labelCol={{ span: 8 }}
                  width="lg"
                  name="siteTag"
                  label="服务器标识"
                  placeholder=""
                  options={OptionsSiteTagList}
                  allowClear={false}
                />
                <ProFormText
                  labelCol={{ span: 8 }}
                  width="lg"
                  name="redisDesc"
                  label="服务器名称"
                  placeholder="redisDesc"
                />
                <ProFormText
                  labelCol={{ span: 8 }}
                  width="lg"
                  name="redisIp"
                  label="redisIP地址"
                  placeholder="redisIP(必填)"
                  rules={[
                    { required: true, message: '不得为空' },
                    {
                      validator: (_, value) => {
                        if (!regexNum.test(value))
                          return Promise.reject(new Error('只支持输入数字和符号.'));
                        if (!regexIP.test(value))
                          return Promise.reject(new Error('格式有误，请检查'));
                        return Promise.resolve();
                      },
                    },
                  ]}
                />
                <ProFormText
                  labelCol={{ span: 8 }}
                  width="lg"
                  name="redisPort"
                  label="端口号"
                  placeholder="redisPort(必填)"
                  rules={[
                    { required: true, message: '不得为空' },
                    {
                      validator: (_, value) => {
                        // const regex = /^[0-9]*$/;
                        const regex = /^\d{4}$/;
                        if (value && !regex.test(value))
                          return Promise.reject(new Error('只支持输入数字且长度为4'));
                        return Promise.resolve();
                      },
                    },
                  ]}
                />
                <ProFormText
                  labelCol={{ span: 8 }}
                  width="lg"
                  name="redisType"
                  label="类型"
                  placeholder="redisType(必填)"
                  rules={[
                    { required: true, message: '不得为空' },
                    {
                      validator: (_, value) => {
                        const regex = /^[a-zA-Z]*$/;
                        if (!regex.test(value))
                          return Promise.reject(new Error('只支持输入大小写字母'));
                        return Promise.resolve();
                      },
                    },
                  ]}
                />
                <ProFormText
                  labelCol={{ span: 8 }}
                  width="lg"
                  name="maxTotal"
                  label="最大分配链接数"
                  placeholder="maxTotal"
                  rules={[{ required: true, message: '不得为空' }]}
                />
                <ProFormText
                  labelCol={{ span: 8 }}
                  width="lg"
                  name="maxIdle"
                  label="最大保持空闲状态链接数"
                  placeholder="maxIdle"
                  rules={[{ required: true, message: '不得为空' }]}
                />
                <ProFormText
                  labelCol={{ span: 8 }}
                  width="lg"
                  name="maxWait"
                  label="当池里没有返回链接，最大等待时间"
                  placeholder="maxWait"
                  rules={[{ required: true, message: '不得为空' }]}
                />
                <ProFormSelect
                  labelCol={{ span: 8 }}
                  width="lg"
                  name="testOnBorrow"
                  label="当调用borrow Object方法时，是否进行有效性检查"
                  placeholder=""
                  options={[
                    { label: '是', value: true },
                    { label: '否', value: false },
                  ]}
                  allowClear={false}
                />
                <ProFormSelect
                  labelCol={{ span: 8 }}
                  width="lg"
                  name="testOnReturn"
                  label="当调用return Object方法时，是否进行有效性检查"
                  placeholder=""
                  options={[
                    { label: '是', value: true },
                    { label: '否', value: false },
                  ]}
                  allowClear={false}
                />
                <ProFormText
                  labelCol={{ span: 8 }}
                  width="lg"
                  name="otherRedisIp"
                  label="备用Redis地址"
                  placeholder="otherRedisIP"
                  // rules={[
                  //   {
                  //     validator: (_, value) => {
                  //       if (!regexNum.test(value))
                  //         return Promise.reject(new Error('只支持输入数字和符号.'));
                  //       if (!regexIP.test(value))
                  //         return Promise.reject(new Error('格式有误，请检查'));
                  //       return Promise.resolve();
                  //     },
                  //   },
                  // ]}
                />
                <ProFormText
                  labelCol={{ span: 8 }}
                  width="lg"
                  name="redis1Cluster"
                  label="Redis1IP地址"
                  placeholder="redis1IP"
                  // rules={[
                  //   {
                  //     validator: (_, value) => {
                  //       if (!regexNum.test(value))
                  //         return Promise.reject(new Error('只支持输入数字和符号.'));
                  //       if (!regexIP.test(value))
                  //         return Promise.reject(new Error('格式有误，请检查'));
                  //       return Promise.resolve();
                  //     },
                  //   },
                  // ]}
                />
                <ProFormText
                  labelCol={{ span: 8 }}
                  width="lg"
                  name="redis2Ip"
                  label="Redis2IP地址"
                  placeholder="redis2IP"
                  // rules={[
                  //   {
                  //     validator: (_, value) => {
                  //       if (!regexNum.test(value))
                  //         return Promise.reject(new Error('只支持输入数字和符号.'));
                  //       if (!regexIP.test(value))
                  //         return Promise.reject(new Error('格式有误，请检查'));
                  //       return Promise.resolve();
                  //     },
                  //   },
                  // ]}
                />
                <ProFormText
                  labelCol={{ span: 8 }}
                  width="lg"
                  name="redis3Cluster"
                  label="Redis3IP地址"
                  placeholder="redis3IP"
                  // rules={[
                  //   {
                  //     validator: (_, value) => {
                  //       if (!regexNum.test(value))
                  //         return Promise.reject(new Error('只支持输入数字和符号.'));
                  //       if (!regexIP.test(value))
                  //         return Promise.reject(new Error('格式有误，请检查'));
                  //       return Promise.resolve();
                  //     },
                  //   },
                  // ]}
                />
                <ProFormText
                  labelCol={{ span: 8 }}
                  width="lg"
                  name="redis4Cluster"
                  label="Redis4IP地址"
                  placeholder="redis4IP"
                  // rules={[
                  //   {
                  //     validator: (_, value) => {
                  //       if (!regexNum.test(value))
                  //         return Promise.reject(new Error('只支持输入数字和符号.'));
                  //       if (!regexIP.test(value))
                  //         return Promise.reject(new Error('格式有误，请检查'));
                  //       return Promise.resolve();
                  //     },
                  //   },
                  // ]}
                />
              </ProForm.Group>
            </>
          </ProForm>
        </>
      </div>
    </PageContainer>
  );
};

export default SensitizeManageDetail;
